package handler

import (
	"strconv"
	"web_framework/model"
	"web_framework/pkg/constvar"
	. "web_framework/pkg/e"
	"web_framework/service"
	"web_framework/storage"
)

//登录身份验证
type GetRouterInfoHandle struct {
}

func (getRouterInfoHandle GetRouterInfoHandle) handleMsg(data model.Request, clientId string) (result model.Response) {
	if data.Mtype == constvar.MtypeAppGetRouterSpeedInfoRequest {
		//检查参数是否为空
		if len(data.Data.Sn) == 0 {
			Log("Info", "sn参数异常")
			return ReturnErr(data.Mid, constvar.MtypeAppGetRouterSpeedInfoResponse, "sn参数异常")
		}

		routerSpeedCacheKey := constvar.RouterRedisPrefix + data.Data.Sn + storage.RedisRouterActualSpeedKey
		res, err := storage.RedisHGetAll(routerSpeedCacheKey)
		if err != nil {
			Log("Info", "获取路由器上下行速度缓存信息失败", err.Error())
			return ReturnErr(data.Mid, constvar.MtypeAppGetRouterSpeedInfoResponse, "获取路由器上下行速度缓存信息失败")
		}
		onlineDeviceList, _ := service.GetOnlineDeviceList(data.Data.Sn)
		offlineDeviceList, _ := service.GetOfflineDeviceList(data.Data.Sn)

		var devices = make([]model.ResponseDevice, 0)
		for _, device := range onlineDeviceList {
			deviceType, _ := strconv.Atoi(device["type"].(string))
			deviceStatus, _ := strconv.Atoi(device["status"].(string))
			deviceInfo := model.ResponseDevice{
				Mac:     device["mac"].(string),
				Name:    device["name"].(string),
				Dspeed:  device["dspeed"].(string),
				Upspeed: device["upspeed"].(string),
				Join:    device["join"].(string),
				Type:    deviceType,
				Status:  deviceStatus,
			}
			devices = append(devices, deviceInfo)
		}
		for _, device := range offlineDeviceList {
			deviceType, _ := strconv.Atoi(device["type"].(string))
			deviceStatus, _ := strconv.Atoi(device["status"].(string))
			deviceOffline, _ := strconv.ParseInt(device["offline"].(string), 10, 64)
			offlineTail := TimeFormatOneDay(deviceOffline, "前")
			deviceInfo := model.ResponseDevice{
				Mac:     device["mac"].(string),
				Name:    device["name"].(string),
				Dspeed:  device["dspeed"].(string),
				Upspeed: device["upspeed"].(string),
				Status:  deviceStatus,
				Offline: offlineTail,
				Join:    device["join"].(string),
				Type:    deviceType,
			}
			devices = append(devices, deviceInfo)
		}
		upSpeed, ok := res["upspeed"]
		if ok == false {
			upSpeed = ""
		}
		downSpeed, ok := res["downspeed"]
		if ok == false {
			downSpeed = ""
		}

		var returnData interface{} = model.ResponseData{
			UpSpeed:   upSpeed.(string),
			DownSpeed: downSpeed.(string),
			Devices:   devices,
		}
		return model.Response{
			Mid:    data.Mid,
			Mtype:  constvar.MtypeAppGetRouterSpeedInfoResponse,
			Info:   "获取速度信息成功",
			Status: constvar.StatusOk,
			Data:   &returnData,
		}
	}
	Log("Info", "获取失败 101")
	return ReturnErr(data.Mid, constvar.MtypeAppGetRouterSpeedInfoResponse, "获取失败")
}
